package cqrtplm.aop;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hustcad.plm.pdm.workitem.model.vo.TyplmWorkItemVO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.entity.WorkItemDO;
import cqrtplm.mapper.WorkItemMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class CreateWorkItemAOP {
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private WorkItemMapper workItemMapper;

    @Around(value = "execution(* com.hustcad.plm.pdm.workitem.controller.TyplmWorkItemController.createWorkItem(..))")
    public Object createWorkItem(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request=(HttpServletRequest) point.getArgs()[1];
        ResponseResult<TyplmWorkItemVO> proceed =(ResponseResult<TyplmWorkItemVO>) point.proceed();
        String name=null;
        try {
            name = ((JSONArray) ((JSONObject) JSONObject.parseObject(request.getParameter("workItemDTO")).get(
                    "ibaAttribute")).get("SBR")).get(0).toString();
        }catch (Exception e) {
            return proceed;
        }
        if (StrUtil.isBlank(name)){
            return proceed;
        }
        String aoid = workItemMapper.selectUserOidByname(name);
        LocalDateTime now = LocalDateTime.now();
        BigInteger oid = proceed.getData().getOid();
        UserDO user = TyAccountContext.getUser();
        WorkItemDO workItemDO = new WorkItemDO();
        workItemDO.setAOId(aoid);
        workItemDO.setOBId(user.getOid().toString());
        workItemDO.setWorkItemID(oid.toString());
        workItemDO.setCreateStamp(now);
        workItemDO.setUpdateStamp(now);
        workItemDO.setModifyStamp(now);
        workItemDO.setUpdateCount(new BigInteger("0"));
        workItemDO.setOId(snowflakeIdComponent.getInstance().nextId().toString());
        workItemDO.setOType("UserWorkLink");
        workItemMapper.insertWorkitemlink(workItemDO);
        return proceed;
    }
}